<template>
  <div class="container">
    <van-cell-group>
      <van-field
        label="姓名"
        placeholder="请输入姓名"
        :value="form.name"
        @change="e => setForm('name', e.mp.detail)"
      />
      <van-field
        label="电话"
        type="number"
        placeholder="请输入手机号"
        :value="form.phone"
        @change="e => setForm('phone', e.mp.detail)"
      />
      <van-field
        label="地区"
        placeholder="请选择省市区"
        :value="areaText"
        readonly
        @click="showArea = true"
      />
      <van-field
        label="详细地址"
        placeholder="街道门牌信息"
        :value="form.address"
        @change="e => setForm('address', e.mp.detail)"
      />
      <van-cell title="设为默认地址">
        <van-switch
          :checked="form.isDefault"
          @change="e => setForm('isDefault', e.mp.detail)"
        />
      </van-cell>
    </van-cell-group>

    <van-popup :show="showArea" position="bottom">
      <van-area
        :area-list="areaList"
        @confirm="onAreaConfirm"
        @cancel="showArea = false"
      />
    </van-popup>

    <view class="address-footer">
      <view class="address-btn" @click="handleSave">确定</view>
    </view>
  </div>
</template>

<script>
import {areaList} from "../../../../store/areaData"
import {showToast} from "../../../../requests/tools";


export default {
  data() {
    return {
      showArea: false,
      form: {
        id: null,
        name: '',
        phone: '',
        area: [],
        address: '',
        isDefault: false
      },
      areaList: areaList,
      isEdit: false
    }
  },

  computed: {
    areaText() {
      return this.form.area.map(item => item.name).join('-')
    }
  },
  //TODO 编辑逻辑
  onLoad(options) {
    if (options.id) {  // 有传入地址ID时
      this.form = { /* 已有地址数据 */ }
      this.isEdit = true // 标记为编辑模式
    } else {
      this.isEdit = false // 标记为新增模式
    }
  },

  methods: {
    setForm(key, value) {
      this.form[key] = value
    },

    onAreaConfirm(e) {
      this.form.area = e.mp.detail.values
      this.showArea = false
    },

    handleSave() {
      if (!this.validateForm()) return
      if (this.isEdit) {
        // 执行更新操作（如调用更新接口）
      } else {
        // 执行新增操作（如调用创建接口）
      }
      mpvue.navigateBack()
    },

    validateForm() {
      if (!this.form.name) {
        showToast('','请输入姓名')
        return false
      }
      if (!/^1\d{10}$/.test(this.form.phone)) {
        showToast('','手机号格式错误')
        return false
      }
      return true
    },
  }
}
</script>

<style>
.address-footer {
  height: 160rpx;
  width: 100%;
  position: fixed;
  left: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #FFFFFF;
}
.address-btn {
  width: 400rpx;
  height: 88rpx;
  border-radius: 44rpx;
  color: #FFFFFF;
  text-align: center;
  line-height: 88rpx;
  margin-left: 26rpx;
  background-color: #E84134;
}

</style>
